<!doctype html>
<html lang="en">
	<head>
		<meta charset="utf-8" />
		<title>3D Product Configurator Demo</title>
		
        <!-- scripts -->
        <!-- we don't need these if we don't use jquery style drag and drop -->	
	    <script type="text/javascript" src="js/jquery-1.8.2.min.js"></script>
	    <script type="text/javascript" src="js/jquery-ui-1.9.1.custom.min.js"></script>

        <!-- 3D related codes -->
		<script type="text/javascript" src="js/webglhelper.js"></script>
        <script type="text/javascript" src="js/three.min.js"></script>
	   	<script type="text/javascript" src="js/ColladaLoader.js"></script>
        <script type="text/javascript" src="js/ReusableRay.js"></script>
	            
    	
	</head>
	<body>
    <!-- This container is where the 3D scene will be located -->
	<div id="container" style="position: absolute;">

	</div>
    <input type="button" onmousedown="startRotatingRight();" onmouseup="stopRotating();" value="TURN LEFT" style="position:absolute; top: 10px; left: 10px;" />
    <input type="button" onmousedown="startRotatingLeft();" onmouseup="stopRotating();" value="TURN RIGHT" style="position:absolute; top: 10px; left: 150px;" />

    <input type="button" onclick="selectPrevObject();" value="Select Previous" style="position:absolute; top: 50px; left: 10px;" />
    <input type="button" onclick="selectNextObject();" value="Select Next" style="position:absolute; top: 50px; left: 150px;" />

    <input type="button" onclick="moveUp();" value="Move Up" style="position:absolute; top: 90px; left: 10px;" />
    <input type="button" onclick="moveDown();" value="Move Down" style="position:absolute; top: 90px; left: 150px;" />

    <select id="model" style="position:absolute; top: 130px; left: 10px;">
        <option value="models/servercomponent1.dae">Server Part1</option>
        <option value="models/servercomponent2.dae">Server Part2</option>
        <option value="models/servercomponent3.dae">Server Part3</option>
    </select>
    <select id="slot" style="position:absolute; top: 130px; left: 150px;">
        <option value="12">12</option><option value="11">11</option><option value="10">10</option>
        <option value="9">9</option><option value="8">8</option><option value="7">7</option>
        <option value="6">6</option><option value="5">5</option><option value="4">4</option>
        <option value="3">3</option><option value="2">2</option><option value="1">1</option>
        <option value="0">Bottom</option>
    </select>
    <input type="button" onclick="addParts($('#model').val(),$('#slot').val(),true);" value="Add New Part" style="position:absolute; top: 155px; left: 10px;" />

	</body>
	<script type="text/javascript">

// TODO : 1) addParts(pathOfTheModelToLoad, pointIn3DSpace)
//		var rackposition = 0;
//		addParts(model, rackposition);

        // Declare variables
	    var container, camera, scene, renderer, projector, directionVector, plane,
        screenW, screenH, ray, theta = 40, rotateDirection = 1, current = 0,
		ROTATESCENE = false, SELECTED = new THREE.Object3D();

	    var pickableObjects = [];

	    ray = new THREE.ReusableRay();
	    projector = new THREE.Projector();
	    directionVector = new THREE.Vector3();

	    screenH = window.innerHeight;
	    screenW = window.innerWidth;

	    var clickInfo = { x: 0, y: 0, userHasClicked: false };
        
        // Initialize the scenes
	    init();
	    animate();

		// Load the server rack and Parts
		// These functions can be called from other frames to trigger
        // location can be modified later to accept x,y,z position.
		addParts('models/serverrack.dae', 0, false);

//		addParts('models/servercomponent1.dae', 2, true);
//		addParts('models/servercomponent1.dae', 3, true);
//		addParts('models/servercomponent1.dae', 4, true);
//		addParts('models/servercomponent2.dae', 8, true);
//		addParts('models/servercomponent3.dae', 9, true);

        //TODO: sort pickable object by it's y position.(so that it will be selected in order)
		
        // -------------------------------------------------------------------------------
		// Utility functions 
		// -------------------------------------------------------------------------------

		function startRotatingRight() { ROTATESCENE = true; rotateDirection = 1;}
		function startRotatingLeft() { ROTATESCENE = true; rotateDirection = -1; }
		function stopRotating() { ROTATESCENE = false; }

		function selectObjectAt(index) {
		    // return the currently selected part to its original y-location
		    pickableObjects[current].position.y = 0;

		    // return the currently selected part to its original y-location
		    pickableObjects[index].position.y = -20;
		    current = index;
        }

		function selectNextObject() {
		    selectObjectAt( (current + 1) % pickableObjects.length );
        }
		function selectPrevObject() {
		    var index;

		    if (current == 0) {
		        index = pickableObjects.length - 1;
		    }
		    else {
		        index = (current - 1) % pickableObjects.length;
		    }
		    selectObjectAt((current + 1) % pickableObjects.length);
		}

		function moveUp() { pickableObjects[current].position.z += 5; }
		function moveDown() { pickableObjects[current].position.z -= 5; }

		function addParts(modelPath, slot, pickable) {			    
			var loader = new THREE.ColladaLoader();
			loader.load(modelPath, function (collada) {
			    var model = collada.scene;

			    model.position.z = 5 * parseInt(slot);
			    model.castShadow = true;
			    model.receiveShadow = true;
			    model.name = "Components:" + modelPath;

			    scene.add(model);

			    if (pickable) pickableObjects.push(model);
			});
		}

		/*
		  Simple example of 3D space
		   +z
		   |
		   |
		   -------+x
		  /
		 /
		-y
		*/

		function init() {
		    // Scene
		    scene = new THREE.Scene();

		    screenW = window.innerWidth;
		    screenH = window.innerHeigh;

		    // create a webGL renderer with antialiasing on
		    renderer = new THREE.WebGLRenderer({ antialias: true, preserveDrawingBuffer: true });
		    renderer.shadowMapEnabled = true;
		    renderer.setSize(screenW, screenH);    
                        
            // Camera
			// parameters :                     FOV, viewport ratio, near plane, far plane
			camera = new THREE.PerspectiveCamera(25, screenW / screenH, 0.1,1000);
			camera.name = 'Camera';
			camera.up = new THREE.Vector3(0, 0, 1); // camera's up vector is z-axis
			scene.add(camera);

			// set the target of the camera (it is where camera is pointing to)
			target = new THREE.Vector3(0, 0, 30);

			// Ground Plane
			var planeGeo = new THREE.PlaneGeometry(200, 200, 10, 10);
			var planeMat = new THREE.MeshLambertMaterial({ color: 0xFFFFFF });
			var plane = new THREE.Mesh(planeGeo, planeMat);
			plane.receiveShadow = true;
			scene.add(plane);

			// Lights
			scene.add(new THREE.AmbientLight(0x505050));

			var light = new THREE.SpotLight(0x505050, 1.5);
                light.position.set(100, 50, 200);
                light.castShadow = true;
            scene.add(light);

            light = new THREE.PointLight(0xffffff, 2, 150);
            light.position.set(0, -50, 100); 
            scene.add(light);
                        

            // Add the renderer to container div
            container = document.createElement('div');
            document.body.appendChild(container);
			container.appendChild(renderer.domElement);

            // Add event handlers
			window.addEventListener('resize', onWindowResize, false);

			onWindowResize();
        }

		function onWindowResize() {
		    screenW = window.innerWidth;
		    screenH = window.innerHeight;

		    camera.aspect = screenW / screenH;
			camera.updateProjectionMatrix();

			renderer.setSize(screenW,screenH);
		}

		function animate() {
			requestAnimationFrame( animate );
			render();
		}

		function render() {
		    if (ROTATESCENE) {
		        theta += 5 * rotateDirection;
            }

            camera.position.x = 200 * Math.sin(theta * Math.PI / 360);
		    camera.position.y = -200 * Math.cos(theta * Math.PI / 360);
		    camera.position.z = 60;
		    camera.lookAt(target);

			renderer.render( scene, camera );
		}		
	</script>
</html>
